package com.medical.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.medical.mapper.SysUserMapper;
import com.medical.model.*;
import com.medical.service.SysRoleService;
import com.medical.service.SysUserRoleService;
import com.medical.service.SysUserService;
import com.medical.util.JWTUtil;
import com.medical.util.WxGetPhoneUtils;
import com.medical.util.common.HttpClientUtil;
import com.medical.util.common.JsonUtils;
import com.medical.util.status.BaseResponse;
import com.medical.util.status.CodeEnum;
import com.medical.util.status.ResponseData;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ziluolan
 * @description: 登录控制层
 * @date 2023/5/9 23:52
 */

@RestController
@RequestMapping("/wx")
public class LoginController {

    @Autowired
    private SysUserService sysUserService;

    @Resource
    SysUserRoleService sysUserRoleService;
    @Resource
    private WX wx;
    @Autowired
    private Audience audience;
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 绑定手机号
     *
     * @param decodePhoneMessage
     * @return
     */
    @PostMapping("/getPhoneNumber")
    @Transactional
    @ApiOperation(value = "绑定手机号")
    public BaseResponse getPhone(@RequestBody DecodePhone decodePhoneMessage, HttpServletRequest request) {

        WXSessionModel user = (WXSessionModel) request.getSession().getAttribute("user");
        SysUser sysUser = new SysUser();
        Phone phone;

        try {
            phone = JsonUtils.jsonToPojo(WxGetPhoneUtils.wxDecrypt(decodePhoneMessage.getEncryptedData(), user.getSession_key(), decodePhoneMessage.getIv()), Phone.class);
            sysUser.setUserToken(user.getOpenid());
            sysUser.setUserId(user.getUserId());
            sysUser.setUserPhone(phone.getPhoneNumber());
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("user_id", user.getUserId());
            sysUserService.update(sysUser, wrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.out(CodeEnum.FAIL, "获取失败");
        }
        return ResponseData.success(phone);
    }

    /**
     * 登录功能
     */
    @PostMapping("/login")
    @Transactional
    @ApiOperation(value = "登录")
    public BaseResponse login(String code, @RequestBody SysUser sysUser) {
        HashMap result = new HashMap();

        WXSessionModel wxSessionModel = null;
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> param = new HashMap<String, String>();
        param.put("appid", wx.getWxId());
        param.put("secret", wx.getWxSecret());
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");
        String wxResult = HttpClientUtil.doGet(url, param);
        wxSessionModel = JsonUtils.jsonToPojo(wxResult, WXSessionModel.class);
        String openid = wxSessionModel.getOpenid();

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_Token", openid);


        if (sysUserService.getOne(queryWrapper) == null) {//第一次登录，加进数据库
            System.out.println(sysUser);
            sysUser.setUserToken(openid);
            sysUser.setUserGender(1);
            sysUserService.save(sysUser);
            sysUserRoleService.setDefaultRole(sysUserService.getOne(queryWrapper));//添加中间表数据
        }
        SysUser loginUser = sysUserService.getOne(queryWrapper);

        List<SysRole> roleList = sysRoleService.list(new QueryWrapper<SysRole>().inSql("id", "select role_id from sys_user_role where user_id=" + loginUser.getUserId()));

        loginUser.setRole(roleList);
        wxSessionModel.setUserId(sysUserService.getOne(queryWrapper).getUserId());

        String jwt = JWTUtil.createJWT(audience, wxSessionModel);

        result.put("user", loginUser);
        result.put("token", jwt);

        return ResponseData.success(result);
    }
}
